package com.waves.search.service.task;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.waves.core.utils.StringUtils;
import com.waves.core.web.domain.TableDataInfo;
import com.waves.search.dto.EsSearchDTO;
import com.waves.search.entity.TaskEs;
import com.waves.search.vo.task.TaskEsVO;
import lombok.RequiredArgsConstructor;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.Criteria;
import org.springframework.data.elasticsearch.core.query.CriteriaQuery;
import org.springframework.data.elasticsearch.core.query.CriteriaQueryBuilder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Eden
 * @date 2024/10/01 10:38
 **/
@Service
@RequiredArgsConstructor
public class TaskSearchServiceImpl implements TaskSearchService {

    private final ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Override
    public TableDataInfo<TaskEsVO> pageTask(EsSearchDTO esSearchDTO) {
        Criteria criteria = new Criteria();
        if (StringUtils.isNotBlank(esSearchDTO.getKeyword())) {
            criteria = Criteria.where(TaskEs.Fields.title)
                    .matches(
                            esSearchDTO.getKeyword());
        }
        CriteriaQuery criteriaQuery = new CriteriaQueryBuilder(criteria)
                .withPageable(esSearchDTO)
                .build();
        SearchHits<TaskEsVO> search = elasticsearchRestTemplate.search(criteriaQuery, TaskEsVO.class);
        Page<TaskEsVO> page = new Page<>();
        List<TaskEsVO> list = new ArrayList<>();
        if (CollUtil.isNotEmpty(search.toList())) {
            for (SearchHit<TaskEsVO> taskEsVOSearchHit : search.toList()) {
                list.add(taskEsVOSearchHit.getContent());
            }
        }
        page.setRecords(list).setCurrent(esSearchDTO.getPageNumber())
                .setSize(esSearchDTO.getPageSize()).setTotal(search.getTotalHits());
        return TableDataInfo.build(page);
    }
}
